/**
 * ReactRouterDom 中实现 登录拦截功能
 *
 *    1. 约定使用 window.isLogin 来作为登录的凭据
 *    2. 将 Route 的 component 修改为 render 渲染方式
 *
 *    定义一个 PrivateRoute 组件，在该组件内渲染 Route 组件，将逻辑封装进去。
 */

import { Component } from "react";
import { Link, Redirect, Route, Switch } from "react-router-dom";

import FilmList from "./views/FilmList";
import Order from "./views/Order";
import Money from "./views/Money";
import Login from "./views/Login";

function PrivateRoute({ component: Component, ...reset }) {
  console.log("reset", reset);
  return (
    <Route
      {...reset}
      render={(props) => {
        const { location } = props;
        if (window.isLogin) {
          return <Component {...props} />;
        } else {
          return (
            <Redirect
              to={{
                pathname: "/login",
                search: "redirect=" + location.pathname + location.search,
              }}
            />
          );
        }
      }}
    />
  );
}

export default class App extends Component {
  render() {
    return (
      <div>
        <h1>App</h1>
        <hr />
        <Link to="/order?id=100">Order</Link> <br />
        <Link to="/money">Money</Link>
        <hr />
        <Switch>
          <Route path="/film-list" component={FilmList} />
          <Route path="/login" component={Login} />

          {/* <Route
            path="/order"
            render={(props) => {
              // 获取到 location
              const { location } = props;
              // 判断是否有登录状态
              if (window.isLogin) {
                // 存在，则表示登录了
                return <Order {...props} />;
              } else {
                // 没有登录，重定向到 登录页面
                return (
                  <Redirect
                    to={{
                      pathname: "/login",
                      search: "redirect=" + location.pathname + location.search,
                    }}
                  />
                );
              }
            }}
          /> */}

          <PrivateRoute path="/order" component={Order} />

          {/* <Route
            path="/money"
            render={(props) => {
              const { location } = props;

              if (window.isLogin) {
                return <Money {...props} />;
              } else {
                return (
                  <Redirect
                    to={{
                      pathname: "/login",
                      search: "redirect=" + location.pathname + location.search,
                    }}
                  />
                );
              }
            }}
          /> */}

          <PrivateRoute path="/money" component={Money} />
        </Switch>
      </div>
    );
  }
}
